package com.tianyi.plugin_echat;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;

import com.echatsoft.echatsdk.core.EChatSDK;
import com.echatsoft.echatsdk.model.ChatParamConfig;
import com.echatsoft.echatsdk.model.VisEvt;
import com.echatsoft.echatsdk.utils.EChatPushManager;

import java.util.Collections;
import java.util.Map;

import io.flutter.app.FlutterApplication;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.view.FlutterView;
import io.flutter.view.TextureRegistry;

/**
 * PluginEchatPlugin
 */
public class PluginEchatPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;
    private Context mContext;
    private Activity activity;
    private static Application application;

    public static void initSDK(Application context, String appId, String appSecret) {
        application = context;
        EChatSDK.init(context, appId, appSecret);
    }

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_plugin_echat");
        channel.setMethodCallHandler(this);
        mContext = flutterPluginBinding.getApplicationContext();
        if (mContext instanceof FlutterApplication) {
            Activity currentActivity = ((FlutterApplication) mContext).getCurrentActivity();
            if (currentActivity != null) {
                activity = currentActivity;
            }
        }
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull final Result result) {
        if (call.method.equals("registerApp")) {
            Map<String, Object> request = (Map<String, Object>) call.arguments;
            String appId = (String) request.get("appId");
            String appSecret = (String) request.get("appSecret");
            if (activity != null) {
                EChatSDK.setDebug(true);
                EChatSDK.init(application, appId, appSecret);

            } else {
                Log.e("PluginEchatPlugin", "activity == null");
            }
            result.success(true);
        } else if (call.method.equals("openEchatSessionWindow")) {
            ChatParamConfig chatParamConfig = new ChatParamConfig();
            if (call.argument("visEvt")!=null){
                Map visEvtMap = call.argument("visEvt");
                String eventId = (String) visEvtMap.get("eventId");
                String title = (String) visEvtMap.get("title");
                String content = (String) visEvtMap.get("content");
                String imageUrl = (String) visEvtMap.get("imageUrl");
                String urlForVisitor = (String) visEvtMap.get("urlForVisitor");
                String urlForStaff = (String) visEvtMap.get("urlForStaff");
                String memo = (String) visEvtMap.get("memo");
                int urlEnableForVisitor = (int) visEvtMap.get("urlEnableForVisitor");
                int visibility = (int) visEvtMap.get("visibility");
                int customizeMsgType = (int) visEvtMap.get("customizeMsgType");
                int dedup = (int) visEvtMap.get("dedup");

                VisEvt visEvt = new VisEvt();
                visEvt.setContent(content);
                visEvt.setCustomizeMsgType(customizeMsgType);
                visEvt.setDedup(dedup);
                visEvt.setEventId(eventId);
                visEvt.setMemo(memo);
                visEvt.setImageUrl(imageUrl);
                visEvt.setTitle(title);
                visEvt.setUrlForStaff(urlForStaff);
                visEvt.setUrlForVisitor(String.valueOf(urlEnableForVisitor));
                visEvt.setVisibility(visibility);
                chatParamConfig.setVisEvt(visEvt);
            }

            String uid = call.argument("uid");
            String metaData = call.argument("metaData");
            String myData = call.argument("myData");
            String lan = call.argument("lan");
            String routeEntranceId = call.argument("routeEntranceId");
            String echatTag = call.argument("echatTag");
            String pushInfo = call.argument("pushInfo");
            String acdStaffId = call.argument("acdStaffId");
            String acdType = call.argument("acdType");
            chatParamConfig.setEchatTag(echatTag);
            chatParamConfig.setLan(lan);
            chatParamConfig.setMetaData(metaData);
            chatParamConfig.setPushInfo(pushInfo);
            chatParamConfig.setRouteEntranceId(Integer.parseInt(routeEntranceId));
            chatParamConfig.setUid(uid);
            chatParamConfig.setMyData(myData);
            EChatSDK.openEChatActivity(activity, chatParamConfig);
            result.success(true);
        } else if (call.method.equals("getUnReadMsgCount")) {
            int unreadCount = EChatPushManager.getInstance().getUnreadCount();
            result.success(Long.bitCount(unreadCount));
        } else if (call.method.equals("getLastMessage")) {
            String lastMessageContent = EChatPushManager.getInstance().getLastMessageContent();
            result.success(lastMessageContent);
        } else if (call.method.equals("closeCurrentConversation")) {
            int closeEChat = EChatSDK.getInstance().closeEChat();
            if (closeEChat == 1) {
                result.success(true);
            } else {
                result.success(false);
            }
        } else if (call.method.equals("logout")) {
            EChatSDK.getInstance().logout(new EChatSDK.VisitorLogoutStatusCallback() {
                @Override
                public void onRemoteStatus(boolean b, String s) {
                   result.success(b);
                }

                @Override
                public void onStatus(boolean b, String s) {
                    result.success(b);
                }
            });
        } else if (call.method.equals("cleanMemory")) {

        } else {
            result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        mContext = binding.getApplicationContext();
        if (mContext instanceof FlutterApplication) {
            Activity currentActivity = ((FlutterApplication) mContext).getCurrentActivity();
            if (currentActivity != null) {
                activity = currentActivity;
            }
        }
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

    }

    @Override
    public void onDetachedFromActivity() {

    }
}
